package com.kuang.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello world!");
        return "index";
    }

    //添加用户
    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }


    //修改用户
    @RequestMapping("/user/update")
    public String update() {
        return "user/update";
    }

    //登录
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    //实现用户认证(用户名 密码)
    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据 UsernamePasswordToken 用户密码令牌
        UsernamePasswordToken token = new UsernamePasswordToken();
        try {
            subject.login(token); //执行登录的方法，如果没有异常就说明,登录成功了！
            return "index";
        } catch (UnknownAccountException e) { //用户名不存在或错误
            model.addAttribute("msg", "用户名错误！");
            return "login";
        } catch (IncorrectCredentialsException e) { //密码不存在或错误
            model.addAttribute("msg", "密码错误！");
            return "login";
        }
    }
}

